package com.cxs.dialogdemo.component;

import com.cxs.dialogdemo.ResourceTable;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

import java.util.Date;

public class CustomComponent extends DirectionalLayout {
    DialogCallback dialogCallback;
    DirectionalLayout layout;
    private String date;
    private DatePicker datePicker;
    private Button btnConfirm;

    public CustomComponent(Context context) {
        super(context);
        // 生成dialog.xml的副本，添加到CustomComponent中
        addComponent(context);
        initView();
        // 设置事件
        initListener(context);
    }

    /*
        生成dialog.xml的副本，添加到CustomComponent中
     */
    private void addComponent(Context context) {
        layout = (DirectionalLayout)LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog, null, false);

        LayoutConfig layoutConfig = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        layout.setLayoutConfig(layoutConfig);

        super.addComponent(layout);
    }

    /*
        获取xml中的子组件
     */
    private void initView() {
        datePicker = (DatePicker)layout.findComponentById(ResourceTable.Id_dialog_datepicker);
        btnConfirm = (Button)layout.findComponentById(ResourceTable.Id_dialog_confirm);
    }
    /*
        设置响应事件
     */
    private void initListener(Context context) {
        btnConfirm.setClickedListener(c -> {
                    int day = datePicker.getDayOfMonth();
                    int month = datePicker.getMonth();
                    int year = datePicker.getYear();
                    date = String.format("%04d年%02d月%02d日", year, month, day);
                    // 回调接口的result方法
                    dialogCallback.result(date);
                });
    }

    /*
        设置事件回调
     */
    public void setDialogCallback(DialogCallback dialogCallback) {
        this.dialogCallback = dialogCallback;
    }

    public interface DialogCallback {
        void result(String a);
    }
}
